package com.strato.rpc.registry.invm.v1_0_0;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import com.strato.annotation.osgi.v1_0_0.service.OsgiService;
import com.strato.rpc.api.v1_0_0.Registry;
import com.strato.rpc.api.v1_0_0.Transport;

@OsgiService(id="rpc.registry.invm")
public class InvmRegistry implements Registry {

	private Map<String,String> _transportRegistry=new HashMap<String,String>();
	private Map<String,Set<String>> _interfaceRegistry=new HashMap<String,Set<String>>();
	
	@Override
	public Object createProxy(String id, Class<?> intf,int retry) {
		String rid=id;
		if(id==null||Transport.AUTO_DETECT.equals(id)){
			if(intf==null){
				return null;
			}
			Set<String> ids = _interfaceRegistry.get(intf.getName());
			if(ids==null||ids.isEmpty()){
				return null;
			}
			rid=ids.iterator().next();
		}
		String transport=_transportRegistry.get(rid);
		if(transport==null){
			return null;
		}
		Transport t=Transport.get(transport);
		return t.createProxy(rid,intf,retry);
	}

	@Override
	public void register(String id, String transport, Object object,Class<?> intf,String bundleName) {
		_transportRegistry.put(id, transport);
		String name=intf.getName();
		Set<String> ids=_interfaceRegistry.get(name);
		if(ids==null){
			ids=new HashSet<String>();
			_interfaceRegistry.put(name, ids);
		}
		ids.add(id);
		Transport t=Transport.get(transport);
		t.export(id,object,intf,bundleName);
	}

	@Override
	public void unregister(String id) {
		String transport=_transportRegistry.remove(id);
		if(transport!=null){
			Transport t=Transport.get(transport);
			t.unexport(id);
		}
	}

}
